//
//  CameraViewController.swift
//  SwiftChatUI
//
//  Created by xzk on 2019/2/26.
//  Copyright © 2019年 xzk. All rights reserved.
//

import UIKit
import AVFoundation

class CameraViewController: UIViewController {
    
    // 捕获设备 (前置，后置，麦克风)
    private var device: AVCaptureDevice?
    
    // 输入设备
    private var input: AVCaptureDeviceInput?
    
    // 输出图片
    private var photoOutput: AVCapturePhotoOutput?
    
    private var session: AVCaptureSession?
    
    private var previewLayer: AVCaptureVideoPreviewLayer?
    
    // 前置后置
    private var position: AVCaptureDevice.Position = .back

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tryOpenCamera()
        
        initView()
    }
    
    private func tryOpenCamera() {
        do {
            device = AVCaptureDevice.default(for: .video)
            input = try AVCaptureDeviceInput(device: device!)
            
            let outputSettings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
            photoOutput = AVCapturePhotoOutput()
            photoOutput?.photoSettingsForSceneMonitoring = outputSettings
            
            session = AVCaptureSession()
            session?.addInput(input!)
            session?.addOutput(photoOutput!)
            
            previewLayer = AVCaptureVideoPreviewLayer(session: session!)
            previewLayer?.videoGravity = .resizeAspectFill
            previewLayer?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
            view.layer.insertSublayer(previewLayer!, at: 0)
            session?.startRunning()
        } catch {
            let alertVC = UIAlertController(title: "失败", message: "相机启动失败", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "好的", style: .default) { (_) in
                self.dismiss(animated: true, completion: nil)
            }
            
            alertVC.addAction(cancelAction)
            
            present(alertVC, animated: true, completion: nil)
        }
    }
    
    private func initView() {
        view.addSubview(progressBtn)
        view.addSubview(switchBtn)
        switchBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(30)
            make.top.equalTo(self.view).offset(50)
            make.right.equalTo(self.view).offset(-50)
        }
    }
    
    @objc private func progressBtnLongClick(_ press: UILongPressGestureRecognizer) {
        if press.state == .began {
            progressBtn.start()
        } else if press.state == .ended {
            progressBtn.stop()
        }
    }
    
    @objc private func progressBtnCick(_ tap: UITapGestureRecognizer) {
        // 捕获照片
        let setting = photoOutput?.photoSettingsForSceneMonitoring
        photoOutput?.capturePhoto(with: setting!, delegate: self)
    }
    
    /// 前摄后摄切换
    @objc private func switchBtnClick() {
        position = (position == .back ? .front : .back)
        
        var newCamera: AVCaptureDevice? = nil
        var newInput: AVCaptureDeviceInput? = nil
        
        let cameras = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: position).devices
        for camera in cameras {
            if camera.position == position {
                newCamera = camera
                break
            }
        }
        
        if let newCamera = newCamera {
            do {
                newInput = try AVCaptureDeviceInput(device: newCamera)
                if let newInput = newInput {
                    // 重置session
                    session?.beginConfiguration()
                    session?.removeInput(input!)
                    if session?.canAddInput(newInput) ?? false {
                        session?.addInput(newInput)
                        input = newInput
                    } else {
                        debugPrint("切换摄像头失败 session设置出错")
                        session?.addInput(input!)
                    }
                    session?.commitConfiguration()
                }
            } catch {
                debugPrint("切换摄像头失败 获取失败")
            }
        }
        
    }
    
    private lazy var progressBtn: ProgressView = {
        let view = ProgressView.init(frame: CGRect(x: (UIScreen.main.bounds.width - 100) * 0.5, y: (UIScreen.main.bounds.height - 200), width: 60, height: 60))
        view.isUserInteractionEnabled = true
        
        // 长按录像
        let press = UILongPressGestureRecognizer(target: self, action: #selector(progressBtnLongClick(_:)))
        view.addGestureRecognizer(press)
        
        // 单点拍照
        let tap = UITapGestureRecognizer(target: self, action: #selector(progressBtnCick(_:)))
        view.addGestureRecognizer(tap)
        
        return view
    }()
    
    private lazy var switchBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "切换"), for: .normal)
        btn.addTarget(self, action: #selector(switchBtnClick), for: .touchUpInside)
        
        return btn
    }()
}

extension CameraViewController: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        let data: Data? = photo.fileDataRepresentation()
        if let image: UIImage = UIImage(data: data ?? Data()) {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
            debugPrint("图片保存成功")
        } else {
            debugPrint("图片获取失败")
        }
    }
}
